#!/bin/bash
# 邮件系统统一管理脚本
# 功能：基于systemd服务管理主程序和同步服务
# 用法: ./run.sh [python解释器路径]
#   例如: ./run.sh python3
#         ./run.sh /www/server/pyporject_evn/versions/3.12.4/bin/python3

# 动态获取项目目录（脚本所在目录）
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Python解释器路径（支持命令行参数或环境变量或默认值）
if [ -n "$1" ]; then
    PYTHON="$1"
elif [ -n "$PYTHON_INTERPRETER" ]; then
    PYTHON="$PYTHON_INTERPRETER"
else
    PYTHON=$(which python3)
fi

# 服务名称
MAIN_SERVICE="mail-server"
SYNC_SERVICE="mail-sync"

# 打印消息
print_info() { echo "[INFO] $1"; }
print_success() { echo "[SUCCESS] $1"; }
print_warning() { echo "[WARNING] $1"; }
print_error() { echo "[ERROR] $1"; }

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查Python版本是否>=3.11
check_python_version() {
    local python_cmd=$1
    
    # 检查Python是否存在
    if ! command -v "$python_cmd" &> /dev/null && [ ! -f "$python_cmd" ]; then
        print_error "Python解释器不存在: $python_cmd"
        return 1
    fi
    
    # 获取Python版本
    local version_output=$("$python_cmd" --version 2>&1)
    local version=$(echo "$version_output" | grep -oP '\d+\.\d+\.\d+' | head -1)
    
    if [ -z "$version" ]; then
        print_error "无法获取Python版本信息"
        return 1
    fi
    
    # 提取主版本号和次版本号
    local major=$(echo "$version" | cut -d. -f1)
    local minor=$(echo "$version" | cut -d. -f2)
    
    # 检查版本是否>=3.11
    if [ "$major" -lt 3 ] || ([ "$major" -eq 3 ] && [ "$minor" -lt 11 ]); then
        print_error "Python版本过低: $version (需要 >= 3.11)"
        return 1
    fi
    
    print_success "Python版本检查通过: $version"
    return 0
}

# 检查Python依赖
check_dependencies() {
    print_info "检查Python依赖..."
    
    local requirements_file="$PROJECT_DIR/api/requirements.txt"
    
    if [ ! -f "$requirements_file" ]; then
        print_error "依赖文件不存在: $requirements_file"
        return 1
    fi
    
    # 获取已安装的包列表（转换为小写，同时保留横线和下划线两种格式）
    local installed_packages=$("$PYTHON" -m pip list --format=freeze 2>/dev/null | cut -d'=' -f1 | tr '[:upper:]' '[:lower:]')
    
    # 动态读取requirements.txt文件中的所有包名
    local missing_deps=()
    
    while IFS= read -r line || [ -n "$line" ]; do
        # 跳过空行和注释行
        [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
        
        # 提取包名（去除版本号和额外参数）
        local package=$(echo "$line" | sed -E 's/[>=<~!]=.*//; s/\[.*\]//; s/[[:space:]].*//; s/^[[:space:]]+//; s/[[:space:]]+$//')
        
        # 跳过空包名
        [ -z "$package" ] && continue
        
        # 转换为小写进行比较（pip包名不区分大小写）
        local package_lower=$(echo "$package" | tr '[:upper:]' '[:lower:]')
        # 同时创建横线转下划线的版本（pip安装后可能转换）
        local package_underscore=$(echo "$package_lower" | tr '-' '_')
        
        # 检查包是否已安装（匹配原名或下划线版本）
        if ! echo "$installed_packages" | grep -qE "^(${package_lower}|${package_underscore})$"; then
            missing_deps+=("$package")
        fi
    done < "$requirements_file"
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        print_warning "缺少以下依赖 (${#missing_deps[@]}个): ${missing_deps[*]}"
        echo "是否自动安装依赖? (y/n)"
        read -r answer
        if [ "$answer" = "y" ]; then
            if install_dependencies; then
                print_success "依赖安装完成"
                return 0
            else
                print_error "依赖安装失败"
                return 1
            fi
        else
            print_error "请手动安装依赖: $PYTHON -m pip install -r $requirements_file"
            return 1
        fi
    else
        print_success "所有依赖已安装"
        return 0
    fi
}

# 安装依赖
install_dependencies() {
    print_info "正在安装Python依赖..."
    
    local requirements_file="$PROJECT_DIR/api/requirements.txt"
    
    if "$PYTHON" -m pip install -r "$requirements_file"; then
        print_success "依赖安装成功"
        return 0
    else
        print_error "依赖安装失败"
        return 1
    fi
}

# 检查服务是否已注册
service_exists() {
    systemctl list-unit-files | grep -q "^$1.service"
}

# 检查服务状态
check_service_status() {
    local service_name=$1
    local display_name=$2
    
    if service_exists "$service_name"; then
        if systemctl is-active --quiet "$service_name"; then
            echo -e "● $display_name: ${GREEN}运行中${NC}"
            return 0
        else
            echo -e "● $display_name: ${RED}已停止${NC}"
            return 1
        fi
    else
        echo -e "● $display_name: ${YELLOW}未注册${NC}"
        return 2
    fi
}

# 检测所有服务状态
check_all_status() {
    echo "=========================================="
    check_service_status "$MAIN_SERVICE" "主程序 (FastAPI)"; MAIN_STATUS=$?
    check_service_status "$SYNC_SERVICE" "同步服务"; SYNC_STATUS=$?
    netstat -tlnp 2>/dev/null | grep ":9999" || ss -tlnp 2>/dev/null | grep ":9999" || echo "  端口 9999 未监听"
    return $(( MAIN_STATUS + SYNC_STATUS ))
}

# 注册主服务
register_main_service() {
    local force_update=$1
    
    if service_exists "$MAIN_SERVICE" && [ "$force_update" != "force" ]; then
        print_warning "主服务已注册"
        return 0
    fi
    
    # 如果服务在运行，先停止
    if service_exists "$MAIN_SERVICE" && systemctl is-active --quiet "$MAIN_SERVICE"; then
        print_info "服务正在运行，先停止..."
        sudo systemctl stop $MAIN_SERVICE
        sleep 1
    fi
    
    print_info "正在注册主服务..."
    
    sudo tee /etc/systemd/system/${MAIN_SERVICE}.service > /dev/null <<EOF
[Unit]
Description=Online Mail Client Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$PROJECT_DIR
ExecStart=$PYTHON $PROJECT_DIR/run/start_server.py
Restart=always
RestartSec=10
StandardOutput=null
StandardError=null

Environment="PYTHONUNBUFFERED=1"
Environment="PYTHONIOENCODING=utf-8"

LimitNOFILE=65535
LimitNPROC=4096
TasksMax=4096
OOMScoreAdjust=-100

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    print_success "主服务已注册: ${MAIN_SERVICE}.service"
}

# 注册同步服务
register_sync_service() {
    local force_update=$1
    
    if service_exists "$SYNC_SERVICE" && [ "$force_update" != "force" ]; then
        print_warning "同步服务已注册"
        return 0
    fi
    
    # 如果服务在运行，先停止
    if service_exists "$SYNC_SERVICE" && systemctl is-active --quiet "$SYNC_SERVICE"; then
        print_info "服务正在运行，先停止..."
        sudo systemctl stop $SYNC_SERVICE
        sleep 1
    fi
    
    print_info "正在注册同步服务..."
    
    sudo tee /etc/systemd/system/${SYNC_SERVICE}.service > /dev/null <<EOF
[Unit]
Description=Mail Sync Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$PROJECT_DIR
ExecStart=$PYTHON $PROJECT_DIR/run/start_sync.py
Restart=always
RestartSec=10
StandardOutput=null
StandardError=null

Environment="PYTHONUNBUFFERED=1"
Environment="PYTHONIOENCODING=utf-8"

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    print_success "同步服务已注册: ${SYNC_SERVICE}.service"
}

# 检测并注册系统服务
check_and_register_service() {
    echo "=========================================="; echo "系统服务检测与注册"; echo "=========================================="
    if service_exists "$MAIN_SERVICE"; then
        print_success "主服务已注册: ${MAIN_SERVICE}.service"; systemctl status ${MAIN_SERVICE}.service --no-pager | head -5
    else
        print_warning "主服务未注册"; echo "是否注册主服务到systemd? (y/n)"; read -r answer
        if [ "$answer" = "y" ]; then register_main_service; fi
    fi
    if service_exists "$SYNC_SERVICE"; then
        print_success "同步服务已注册: ${SYNC_SERVICE}.service"; systemctl status ${SYNC_SERVICE}.service --no-pager | head -5
    else
        print_warning "同步服务未注册"; echo "是否注册同步服务到systemd? (y/n)"; read -r answer
        if [ "$answer" = "y" ]; then register_sync_service; fi
    fi
    echo "=========================================="
}

# 重新注册服务（强制更新）
reregister_services() {
    echo "=========================================="; echo "重新注册系统服务"; echo "=========================================="
    echo "选择要重新注册的服务:"; echo "1. 主程序"; echo "2. 同步服务"; echo "3. 全部服务"; echo "0. 取消"
    read -p "请选择: " choice
    case $choice in
        1) register_main_service "force" ;;
        2) register_sync_service "force" ;;
        3) register_main_service "force"; register_sync_service "force" ;;
        0) print_info "已取消"; return ;;
        *) print_error "无效选择"; return ;;
    esac
    echo "=========================================="
}

# 启动服务
start_service() {
    local service_name=$1
    local display_name=$2
    
    if ! service_exists "$service_name"; then
        print_error "$display_name 未注册，请先注册服务"
        return 1
    fi
    
    print_info "启动 $display_name..."; sudo systemctl start $service_name; sleep 2
    if systemctl is-active --quiet $service_name; then
        print_success "$display_name 已启动"
    else
        print_error "$display_name 启动失败"; echo "查看日志："; sudo journalctl -u $service_name -n 20 --no-pager
        return 1
    fi
}

# 停止服务
stop_service() {
    local service_name=$1
    local display_name=$2
    
    if ! service_exists "$service_name"; then
        print_warning "$display_name 未注册"
        return 0
    fi
    
    print_info "停止 $display_name..."; sudo systemctl stop $service_name; sleep 1
    if ! systemctl is-active --quiet $service_name; then
        print_success "$display_name 已停止"
    else
        print_warning "$display_name 停止失败，尝试强制停止..."; sudo systemctl kill $service_name; sleep 1
        print_success "$display_name 已强制停止"
    fi
}

# 重启服务
restart_service() {
    local service_name=$1
    local display_name=$2
    
    if ! service_exists "$service_name"; then
        print_error "$display_name 未注册，请先注册服务"
        return 1
    fi
    
    print_info "重启 $display_name..."; sudo systemctl restart $service_name; sleep 2
    if systemctl is-active --quiet $service_name; then
        print_success "$display_name 已重启"
    else
        print_error "$display_name 重启失败"; return 1
    fi
}

# 查看主程序日志
view_main_logs() {
    if service_exists "$MAIN_SERVICE"; then
        print_info "查看主程序服务日志 (实时100条，Ctrl+C退出)"
        sleep 1
        sudo journalctl -u $MAIN_SERVICE -n 100 -f
    else
        print_error "主服务未注册"
    fi
}

# 查看同步服务日志
view_sync_logs() {
    if service_exists "$SYNC_SERVICE"; then
        print_info "查看同步服务日志 (实时100条，Ctrl+C退出)"
        sleep 1
        sudo journalctl -u $SYNC_SERVICE -n 100 -f
    else
        print_error "同步服务未注册"
    fi
}

# 查看实时日志
view_real_time_log() {
    local log_type=$1
    local log_file="$PROJECT_DIR/runtime/logs/${log_type}.log"

    if [ ! -f "$log_file" ]; then
        print_error "日志文件不存在: $log_file"
        return
    fi

    print_info "查看 ${log_type} 日志 (动态查看最后50行, Ctrl+C退出)"
    sleep 1
    tail -f -n 50 "$log_file"
}

# 启用开机自启
enable_autostart() {
    echo "=========================================="; echo "启用开机自启"; echo "=========================================="
    if service_exists "$MAIN_SERVICE"; then
        sudo systemctl enable $MAIN_SERVICE; print_success "主服务开机自启已启用"
    else print_warning "主服务未注册"; fi
    if service_exists "$SYNC_SERVICE"; then
        sudo systemctl enable $SYNC_SERVICE; print_success "同步服务开机自启已启用"
    else print_warning "同步服务未注册"; fi
    echo "=========================================="
}

# 禁用开机自启
disable_autostart() {
    echo "=========================================="; echo "禁用开机自启"; echo "=========================================="
    if service_exists "$MAIN_SERVICE"; then
        sudo systemctl disable $MAIN_SERVICE; print_success "主服务开机自启已禁用"
    else print_warning "主服务未注册"; fi
    if service_exists "$SYNC_SERVICE"; then
        sudo systemctl disable $SYNC_SERVICE; print_success "同步服务开机自启已禁用"
    else print_warning "同步服务未注册"; fi
    echo "=========================================="
}

# 删除服务
delete_service() {
    local service_name=$1
    local display_name=$2

    if ! service_exists "$service_name"; then
        print_warning "$display_name 未注册"
        return 0
    fi

    print_info "正在删除 $display_name..."

    # 停止服务
    if systemctl is-active --quiet "$service_name"; then
        sudo systemctl stop "$service_name"
        print_info "$display_name 已停止"
    fi

    # 禁用开机自启
    if systemctl is-enabled --quiet "$service_name"; then
        sudo systemctl disable "$service_name"
        print_info "$display_name 开机自启已禁用"
    fi

    # 删除服务文件
    sudo rm "/etc/systemd/system/${service_name}.service"
    print_info "服务文件已删除: /etc/systemd/system/${service_name}.service"

    sudo systemctl daemon-reload
    print_success "$display_name 已成功删除"
}

# 删除服务菜单
manage_delete_service() {
    echo "=========================================="
    echo "删除系统服务"
    echo "=========================================="
    echo "警告：此操作将彻底删除服务配置文件，但不会删除项目文件。"
    echo "选择要删除的服务:"
    echo "  1. 主程序"
    echo "  2. 同步服务"
    echo "  3. 全部服务"
    echo "  0. 取消"
    read -p "请选择: " choice
    case $choice in
        1) delete_service "$MAIN_SERVICE" "主程序" ;;
        2) delete_service "$SYNC_SERVICE" "同步服务" ;;
        3) delete_service "$MAIN_SERVICE" "主程序"; delete_service "$SYNC_SERVICE" "同步服务" ;;
        0) print_info "已取消"; return ;;
        *) print_error "无效选择"; return ;;
    esac
    echo "=========================================="
}

# 主菜单
show_menu() {
    clear
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}   邮件服务管理系统 (Systemd)${NC}($PROJECT_DIR)"
    
    # 显示Python版本信息
    if command -v "$PYTHON" &> /dev/null || [ -f "$PYTHON" ]; then
        local py_version=$("$PYTHON" --version 2>&1 | grep -oP '\d+\.\d+\.\d+' | head -1)
        if [ -n "$py_version" ]; then
            echo "Python版本: $py_version($PYTHON)"
        fi
    fi
    
    check_all_status
    echo "=========================================="
    echo "操作菜单"
    echo "=========================================="
    echo "【系统服务管理】"
    echo "  1. 检测并注册系统服务    2. 重新注册系统服务"
    echo "  3. 启用开机自启          4. 禁用开机自启"
    echo "  5. 删除服务"
    echo "【主程序管理 (Systemd)】"
    echo "  6. 启动  7. 停止  8. 重启  9. 查看服务日志"
    echo "【同步服务管理 (Systemd)】"
    echo "  10. 启动  11. 停止  12. 重启  13. 查看服务日志"
    echo "【实时文件日志】"
    echo "  14. 查看Info日志         15. 查看Error日志"
    echo "  16. 查看Debug日志        17. 查看Sync日志"
    echo "【其他】"
    echo "  18. 安装/更新依赖  19. 查看系统资源  0. 退出"
    echo "=========================================="
}

# 初始化检查
init_check() {
    # 检查Python版本
    if ! check_python_version "$PYTHON"; then
        print_error "Python版本检查失败，请使用正确的Python解释器"
        echo "用法: $0 [python解释器路径]"
        echo "示例: $0 python3"
        echo "      $0 /www/server/pyporject_evn/versions/3.12.4/bin/python3"
        exit 1
    fi
    
    # 检查依赖
    if ! check_dependencies; then
        print_error "依赖检查失败，请先安装依赖"
        exit 1
    fi
}

# 首次运行时执行初始化检查
init_check

# 主循环
while true; do
    show_menu
    read -p "请选择操作 [0-19]: " choice
    
    case $choice in
        1) check_and_register_service ;;
        2) reregister_services ;;
        3) enable_autostart ;;
        4) disable_autostart ;;
        5) manage_delete_service ;;
        6) start_service "$MAIN_SERVICE" "主程序" ;;
        7) stop_service "$MAIN_SERVICE" "主程序" ;;
        8) restart_service "$MAIN_SERVICE" "主程序" ;;
        9) view_main_logs; continue ;;
        10) start_service "$SYNC_SERVICE" "同步服务" ;;
        11) stop_service "$SYNC_SERVICE" "同步服务" ;;
        12) restart_service "$SYNC_SERVICE" "同步服务" ;;
        13) view_sync_logs; continue ;;
        14) view_real_time_log "info"; continue ;;
        15) view_real_time_log "error"; continue ;;
        16) view_real_time_log "debug"; continue ;;
        17) view_real_time_log "sync"; continue ;;
        18) install_dependencies ;;
        19) bash "$PROJECT_DIR/run/check_resources.sh" 2>/dev/null || print_warning "资源检测脚本不存在" ;;
        0) print_info "退出管理脚本"; exit 0 ;;
        *) print_error "无效选择，请重新输入" ;;
    esac
    
    read -p "按Enter键继续..."
done